/**
 *
 */
package util;

import android.os.Handler;
import android.os.Message;

import listener.OnDownloadListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author Crystalline
 * @GiteePage https://gitee.com/crystallineDW/krn
 */
public class DownloadUtil {
    private OnDownloadListener LOCALlistener;
    public void DownloadGET(final OkHttpClient HttpClient, final String url, final String SavePath, final String FileName, boolean IsOverWrite, OnDownloadListener listener){
        LOCALlistener = listener;
        File folder = new File(SavePath);
        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdirs();
        }
        folder = null;
        File file = new File(SavePath+FileName);

        if (!file.exists()) {
            //nofile
            final Request Getrequest = new Request.Builder()
                    .url(url)
                    .build();



            start(HttpClient,Getrequest,checkPath(SavePath,FileName),listener);
        } else {
            //hasfile
            if(IsOverWrite){
                //overwrite
                final Request Getrequest = new Request.Builder()
                        .url(url)
                        .build();

                start(HttpClient,Getrequest,checkPath(SavePath,FileName),listener);
            }else{
                //skin
                listener.onDownload_Success(file);
            }

        }
    }



    public void DownloadPOST(final OkHttpClient HttpClient, final String url, final Map<String,String> post_map, final String SavePath,final String FileName,boolean IsOverWrite, OnDownloadListener listener){
        LOCALlistener = listener;
        //检查父路径
        File folder = new File(SavePath);
        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdirs();
        }
        folder = null;

        //检查文件是否存在
        File file = new File(SavePath+FileName);

        if (!file.exists()) {
            //nofile
            RequestBody body = null;

            if(post_map!=null)
            {
                FormBody.Builder post_data = new FormBody.Builder();

                for(Map.Entry<String, String> entry : post_map.entrySet()){
                    String mapKey = entry.getKey();
                    String mapValue = entry.getValue();
                    post_data.add(mapKey,mapValue);
                }
                body = post_data.build();
            }
            Request Postrequest = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            start(HttpClient,Postrequest,checkPath(SavePath,FileName),listener);
        } else {
            //hasfile
            if(IsOverWrite){
                //overwrite

                RequestBody body = null;

                if(post_map!=null)
                {
                    FormBody.Builder post_data = new FormBody.Builder();

                    for(Map.Entry<String, String> entry : post_map.entrySet()){
                        String mapKey = entry.getKey();
                        String mapValue = entry.getValue();
                        post_data.add(mapKey,mapValue);
                    }
                    body = post_data.build();
                }
                Request Postrequest = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                start(HttpClient,Postrequest,checkPath(SavePath,FileName),listener);
            }else{
                //skin
                listener.onDownload_Success(file);
            }

        }




    }

    public void start(OkHttpClient HttpClient, Request request, final String CompletePath, final OnDownloadListener listener){
        LOCALlistener = listener;
        HttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onDownload_Fail(e);
            }
            /*
             * 首先将服务器返回的文件数据response放入到InputStream输入流中，然后将流通过字节数组byte读取，读到最后一位添加到FileOutputStream文件输出流中，
             * 同时文件输出流存入创建的文件File的路径下。最后关闭流，自此文件下载完成。
             * **/

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;//输入流
                byte[] buf = new byte[2048];//定义一个字节数组,相当于缓存
                int len = 0;//得到实际读取到的字节数 读到最后返回-1
                FileOutputStream fos = null;//文件输出流
                try {

                    is = response.body().byteStream();//获得服务器返回数据//response服务器返回数据；RequestBody存放待提交数据
                    long total = response.body().contentLength();//获取文件大小
                    long sum = 0;
                    fos = new FileOutputStream(new File(CompletePath));
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        final double progress = (double) (sum * 100.0 / total);

                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = progress;
                        handler.sendMessage(msg);
                    }
                    fos.flush();
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(getActivity(), "下载成功", Toast.LENGTH_LONG).show();
//                        }
//                    });

                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = new File(CompletePath);
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = e;
                    handler.sendMessage(msg);

                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = e;
                        handler.sendMessage(msg);
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = e;
                        handler.sendMessage(msg);
                    }
                }
            }
        });


    }

    private String checkPath(String SavePath,String FileName){

        String finalpath = SavePath+FileName;
        if (finalpath.indexOf("\\"+FileName)==-1)
        {
            //没有补全"\"
            finalpath = SavePath+"\\"+FileName;
        }
        if (finalpath.indexOf("/"+FileName)==-1){
            //没有补全"/"
            finalpath = SavePath+"/"+FileName;
        }
        return finalpath;
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    //error
                    IOException e = (IOException) msg.obj;
                    LOCALlistener.onDownload_Fail(e);
                    break;
                case 1:
                    //downloading
                    double progress = (double) msg.obj;
                    LOCALlistener.onDownload_Downloading(progress);
                    break;
                case 2:
                    //ok
                    File out = (File) msg.obj;
                    LOCALlistener.onDownload_Success(out);
                    break;
            }
        }
    };

}
